const graphql = require("graphql");
const {GraphQLSchema, GraphQLObjectType, GraphQLList, GraphQLString} = graphql;

//////////////////////定义类型////////////////////////////

const Todo = new GraphQLObjectType({
	name: "Todo",
	fields: {
		title: {
			type: GraphQLString,
			resolve(parentValue, args, req){
				return parentValue.title + "!";
			}
		}
	}
});

const User = new GraphQLObjectType({
	name: "User",
	args: {
		name: {type: GraphQLString}
	},
	fields: {
		name: {type: GraphQLString},
		sex: {type: GraphQLString},
		todoLists: {
			type: new GraphQLList(Todo),
			args: {
				tag: {type: GraphQLString}
			},
			resolve(parentValue, args, req) {
				return parentValue.todoLists.map(v => ({title: v + args.tag}));
			}
		}
	}
});

//////////////////////定义查询////////////////////////////

const userQuery = {
	type: User,
	args: {
		name: {type: GraphQLString}
	},
	resolve: (_, {name}, req) => {
		// 这里还能做鉴权
		console.log('query signedCookies:', req.signedCookies);
		return {
			name: name,
			sex: "M",
			todoLists: ["1", "2", "3"]
		}
	}
};
/*
const todoListQuery = {
	type: graphql.GraphQLString,
	args: {
		userId: {type: GraphQLString}
	},
	resolve: (_, {userId}) => "a1"
};
*/
const queryType = new GraphQLObjectType({
	name: "Query",
	fields: {
		user: userQuery
	}
});

const Schema = new GraphQLSchema({
	query: queryType
});

module.exports = Schema;

// 如何表示非空参数 和 返回值
// 定义 class 处理各种 API，结合 root 参数
// 感觉其实只使用 GraphQLObjectType 也可以